package view;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import controller.ServidorSocket;

public class Servidor extends javax.swing.JFrame {

  private static final long serialVersionUID = 1L;

  ServidorSocket socket = null;

  private javax.swing.JPanel cabecalhoPanel;
  private javax.swing.JLabel tituloCabecalho;
  private javax.swing.JSeparator separadorCabecalho;

  private javax.swing.JPanel conteudoPanel;
  private javax.swing.JLabel ipServidorLabel;
  private javax.swing.JScrollPane scrollConteudo;
  private static javax.swing.JTextArea txtDetalhes;
  private static javax.swing.JTextField txtIPservidor;

  private javax.swing.JButton iniciarButton;
  //private javax.swing.JButton limparLog;

  public Servidor() {
    //inicializando componentes visuais da interface
    initComponents();
    // centralizando interface na tela do usuario
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = getSize();
    setLocation(new Point((screenSize.width - frameSize.width) / 2,
                          (screenSize.height - frameSize.width) / 2));
    // bloqueando redimensionamento da interface
    this.setResizable(false);
    this.addWindowListener(new WindowListener() {
		
		public void windowOpened(WindowEvent e) {
			
		}
		
		public void windowIconified(WindowEvent e) {
			
			
		}
		
		public void windowDeiconified(WindowEvent e) {
			
			
		}
		
		public void windowDeactivated(WindowEvent e) {
			
			
		}
		
		public void windowClosing(WindowEvent e) {
			try{
				Date hoje = new Date();
		        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HHmmss"); 
		        String hj = formatter.format(hoje); 
		        
		        FileWriter fw = new FileWriter("log/" + hj + ".log");

		        fw.write(txtDetalhes.getText());
		        fw.close();
		        
	        } catch(Exception ex) { 
	        	ex.printStackTrace(); 
	        } 
		}
		
		public void windowClosed(WindowEvent e) {
			
		}
		
		public void windowActivated(WindowEvent e) {
			
			
		}
	});
  }

  private void initComponents() {

    setTitle("Controle de Transito - SO 2009.2");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

    cabecalhoPanel = new javax.swing.JPanel();
    tituloCabecalho = new javax.swing.JLabel();
    separadorCabecalho = new javax.swing.JSeparator();
    conteudoPanel = new javax.swing.JPanel();
    ipServidorLabel = new javax.swing.JLabel();
    txtIPservidor = new javax.swing.JTextField();
    scrollConteudo = new javax.swing.JScrollPane();
    txtDetalhes = new javax.swing.JTextArea();
    iniciarButton = new javax.swing.JButton();
    //limparLog = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    tituloCabecalho.setFont(new java.awt.Font("Trebuchet MS", 1, 12));
    tituloCabecalho.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    tituloCabecalho.setText("Sistema de Controle de Trafego");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(cabecalhoPanel);
    cabecalhoPanel.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
                                     jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                     .addGroup(jPanel1Layout.createSequentialGroup()
                                               .addContainerGap()
                                               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                         .addComponent(separadorCabecalho, javax.swing.GroupLayout.PREFERRED_SIZE, 475, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                         .addComponent(tituloCabecalho, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE))
                                                         .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
                                   jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addGroup(jPanel1Layout.createSequentialGroup()
                                             .addComponent(tituloCabecalho, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                                             .addGap(8, 8, 8)
                                             .addComponent(separadorCabecalho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                             .addContainerGap())
    );

    ipServidorLabel.setText("IP do Servidor:");

    txtIPservidor.setEditable(false);
    txtIPservidor.setFont(new java.awt.Font("Tahoma", 1, 18));
    txtIPservidor.setText(getIP());

    txtDetalhes.setColumns(20);
    txtDetalhes.setEditable(false);
    txtDetalhes.setRows(5);
    txtDetalhes.setText("");
    scrollConteudo.setViewportView(txtDetalhes);

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(conteudoPanel);
    conteudoPanel.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
                                     jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                     .addGroup(jPanel2Layout.createSequentialGroup()
                                               .addContainerGap()
                                               .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                         .addComponent(scrollConteudo, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                                                         .addGroup(jPanel2Layout.createSequentialGroup()
                                                                   .addComponent(ipServidorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                   .addGap(18, 18, 18)
                                                                   .addComponent(txtIPservidor, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                                   .addContainerGap())
    );
    jPanel2Layout.setVerticalGroup(
                                   jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addGroup(jPanel2Layout.createSequentialGroup()
                                             .addContainerGap()
                                             .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                       .addComponent(txtIPservidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                       .addComponent(ipServidorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                       .addComponent(scrollConteudo, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE))
    );


    iniciarButton.setText("Iniciar Servidor");
    iniciarButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        socket = new ServidorSocket();
        socket.start();
        iniciarButton.setEnabled(false);
      }
    });

    //limparLog.setText("Limpar Log");
    /*limparLog.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        stxtDetalhes.setText("");
      }
    });*/

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
                              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                              .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                  .addGroup(layout.createSequentialGroup()
                                                            .addGap(200, 200, 200)
                                                            .addComponent(iniciarButton)
                                                            .addGap(29, 29, 29))
                                                            .addComponent(cabecalhoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                            .addContainerGap())
                                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                      .addGroup(layout.createSequentialGroup()
                                                                                .addContainerGap()
                                                                                .addComponent(conteudoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                                .addContainerGap()))
    );
    layout.setVerticalGroup(
                            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                      .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 415, Short.MAX_VALUE)
                                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(iniciarButton))
                                                .addContainerGap())
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                          .addGroup(layout.createSequentialGroup()
                                                                    .addGap(50, 50, 50)
                                                                    .addComponent(conteudoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addContainerGap(43, Short.MAX_VALUE)))
    );

    pack();
  }
  

  public static void mensagem(final String mensagem)
  {
    try
    {
      java.awt.EventQueue.invokeAndWait(new Runnable()
      {
        public void run()
        {
          txtDetalhes.setText(txtDetalhes.getText() + "\n" + mensagem);
        }
      });
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
    catch (InvocationTargetException e)
    {
      e.printStackTrace();
    }
  }
  

  public static void mensagemSucesso(String mensagem) {
    mensagem("[SUCESSO] " + mensagem);
  }

  public static void mensagemInformacao(String mensagem) {
    mensagem("[INFO] " + mensagem);
  }

  public static void mensagemAviso(String mensagem) {
    mensagem("[AVISO] " + mensagem);
  }

  public static void mensagemErro(String mensagem) {
    mensagem("[ERRO] " + mensagem);
  }

  public static void setDetalhes(String msg) {
    txtDetalhes.setText(msg);
  }

  public static void appendDetalhes(String msg) {
    txtDetalhes.setText(msg + "\n" + txtDetalhes.getText());
  }

  public static void setIP(String msg) {
    txtIPservidor.setText(msg);
  }

  @SuppressWarnings("unchecked")
  public String getIP() {
    Enumeration nis = null;
    String ip = "";

    try {
      nis = NetworkInterface.getNetworkInterfaces();
      while (nis.hasMoreElements()) {  
        NetworkInterface ni = (NetworkInterface) nis.nextElement();  
        Enumeration ias = ni.getInetAddresses();

        while (ias.hasMoreElements()) {  
          InetAddress ia = (InetAddress) ias.nextElement();
          if (!ni.getName().equals("lo")){
            if(!ia.getHostAddress().contains(":")) {
              ip = ia.getHostAddress();
              return ip;
            }
          }   
        }  
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }
    return "fora da rede";
  }
  
}